package com.hang.ad.index.interest;

import com.hang.ad.index.IndexAware;
import com.hang.ad.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

@Slf4j
@Component
public class UnitInterestIndex implements IndexAware<String, Set<Long>> {
    private static Map<String, Set<Long>> itTagMap;
    private static Map<Long, Set<String>> unitIdMap;

    static {
        itTagMap = new ConcurrentHashMap<>();
        unitIdMap = new ConcurrentHashMap<>();
    }
    @Override
    public Set<Long> get(String key) {

        return itTagMap.get(key);
    }

    @Override
    public void update(String key, Set<Long> value) {
        log.error("不支持update");
    }

    @Override
    public void add(String key, Set<Long> value) {
        Set<Long> unitIds = CommonUtils.getOrCreate(key, itTagMap, ConcurrentSkipListSet::new);
        unitIds.addAll(value);
        for (Long id : value){
            Set<String> itTags = CommonUtils.getOrCreate(id, unitIdMap, ConcurrentSkipListSet::new);
            itTags.add(key);
        }
    }

    @Override
    public void delete(String key, Set<Long> value) {
        Set<Long> unitIds = CommonUtils.getOrCreate(key, itTagMap, ConcurrentSkipListSet::new);
        unitIds.removeAll(value);
        for (Long id : value){
            Set<String> itTags = CommonUtils.getOrCreate(id, unitIdMap, ConcurrentSkipListSet::new);
            itTags.remove(key);
        }
    }

    public boolean match(Long unitId, List<String> itTags){
        if (unitIdMap.containsKey(unitId) && CollectionUtils.isNotEmpty(unitIdMap.get(unitId))){
            Set<String> itTagSet = unitIdMap.get(unitId);
            return CollectionUtils.isSubCollection(itTags, itTagSet);
        }
        return false;
    }
}
